import type { Slide, PPTElement } from '@/types/slides'
import { GetTemplateItemData } from './checkTemplate'
import { nanoid } from 'nanoid'

/**
 * @name 生成两张图片和一段文本的幻灯片
 * @param tempId 模板ID
 * @param params 
 * @returns 
 */
export async function GetThreeImgAndTxtContCourseware(tempId: string, params: PPTManyImgManyTxtDataSchema): Promise<Slide | undefined> {
  const tempData = await GetTemplateItemData(tempId, 'txtAndThreeImg')
  if (!tempData) return

  let str = JSON.stringify(tempData.default)
  str = str.replace('%幻灯片章节%', params.group)
  str = str.replace('%幻灯片段落%', params.txt.join(''))
  const contItem = JSON.parse(str)

  let max = 0
  const ids = ['%幻灯片图片一%', '%幻灯片图片二%', '%幻灯片图片三%']
  if (params.img.length > 3) {
    max = 3
  }
  else {
    max = params.img.length
  }

  for (let i = 0; i < max; i++) {
    const imgPPTIndex = contItem.elements.findIndex((el: PPTElement) => el.type === 'shape' && el.text?.content.includes(ids[i]))

    if (imgPPTIndex !== -1) {
      const item = contItem.elements[imgPPTIndex]
      const imagePPTEl = {
        'type': 'image',
        'id': imgPPTIndex,
        'src': params.img[i],
        'width': item.width,
        'height': item.height,
        'left': item.left,
        'top': item.top,
        'fixedRatio': true,
        'rotate': 0
      }
  
      contItem.elements.splice(imgPPTIndex, 1, imagePPTEl)
    }
  }

  contItem.id = nanoid(10)
  contItem.elements.forEach((el: any) => {
    el.id = nanoid(10)
  })
  return contItem
}
